import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;

import java.io.IOException;
import java.text.Format;
import java.text.SimpleDateFormat;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import devboard.dbutil.MongoUtil;

/**
 * Servlet implementation class ChatHandler
 */
@WebServlet("/ChatHandler")
public class ChatHandler extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ChatHandler() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		long lastUpdate=Long.parseLong(request.getParameter("lastUpdate"));
		DBCollection chat=MongoUtil.getCollection("Chat");
		DBCursor cursor=chat.find(new BasicDBObject("time",
				new BasicDBObject("$gt",lastUpdate))).sort(new BasicDBObject("time",1));
		String res="";
		if((lastUpdate==0)&&(cursor.size()>30)){
			cursor.skip(cursor.size()-30);
		}
		DBObject message;
		Format formater=new SimpleDateFormat("HH.mm.ss");
		while(cursor.hasNext()){
			message=cursor.next();
			if(!message.get("ownerId").equals(request.getSession().getAttribute("ownerId"))){
				request.getSession().setAttribute("ownerId",message.get("ownerId").toString());
				res+="<hr /><pre style=\"text-align:right;\">"+formater.format(((Long)message.get("time")))
						+"\t<b>"+message.get("owner")+"</b></pre>";
			}
			res+="<div><em>"+message.get("text")+"</em></div><br>";
			lastUpdate=(Long)(message.get("time"));
		}
		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().print(lastUpdate+"|"+res);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String text=request.getParameter("message");
		text=text.replaceAll("&", "&amp;");
		text=text.replaceAll("<", "&lt;");
		text=text.replaceAll(">", "&gt;");
		MongoUtil.sendMessage(text, (String)request.getSession().getAttribute("firstName")+" "+
				(String)request.getSession().getAttribute("lastName"),(String)request.getSession().getAttribute("_id"));
	}

}
